/**
 * 账户余额状态管理
 */
import { defineStore } from 'pinia';
// 修改类型导入路径，将首字母大写的Account改为小写的account
import type { RechargeRequest, RechargeRecordsResponse, BalanceRecordsResponse } from '@/types/account/Account';
import * as accountAPI from '@/api/account/account';
export const useAccountStore = defineStore('account', {
  state: () => ({
    /** 账户余额信息 */
    balance: 0 as number,
    /** 余额加载状态 */
    loading: false as boolean,
    /** 充值加载状态 */
    rechargeLoading: false as boolean,
    /** 错误信息 */
    error: null as string | null,
    /** 充值记录 */
    rechargeRecords: null as RechargeRecordsResponse | null,
    /** 余额记录 */
    balanceRecords: null as BalanceRecordsResponse | null
  }),
  
  // 修改为正确的持久化配置
  persist: {
    key: 'account_store',
    storage: localStorage,
    pick: ['balance'] // 使用pick而不是paths来指定要持久化的字段
  },
  
  getters: {
    /** 格式化后的余额，保留两位小数 */
    formattedBalance: (state) => {
      return state.balance.toFixed(2);
    },
    getBalance: (state) => state.balance
  },
  
  actions: {
    /**
     * 获取账户余额
     */
    async fetchAccountBalance() {
      this.loading = true;
      this.error = null;
      try {
        const data = await accountAPI.getAccountBalance();
        // console.log("data"+JSON.stringify(data));
        this.balance = (data && data.balance) ? data.balance : 0;
        console.log("this.balance"+this.balance);
        return data;
      } catch (err) {
        this.error = '获取账户余额失败，请重试';
        console.error('获取账户余额失败:', err);
        throw err;
      } finally {
        this.loading = false;
      }
    },
    
    /**
     * 账户充值
     * @param rechargeRequest 充值请求参数
     */
    async recharge(rechargeRequest: RechargeRequest) {
      this.rechargeLoading = true;
      this.error = null;
      try {
        const data = await accountAPI.rechargeAccount(rechargeRequest);
        // 充值成功后刷新余额
        await this.fetchAccountBalance();
        return data;
      } catch (err) {
        this.error = '充值失败，请重试';
        console.error('充值失败:', err);
        throw err;
      } finally {
        this.rechargeLoading = false;
      }
    },
    
    /**
     * 获取充值记录
     * @param params 分页参数
     */
    async fetchRechargeRecords(params?: { page?: number; limit?: number }) {
      try {
        const data = await accountAPI.getRechargeRecords(params);
        this.rechargeRecords = data;
        return data;
      } catch (err) {
        console.error('获取充值记录失败:', err);
        throw err;
      }
    },
    
    /**
     * 获取余额明细
     * @param params 查询参数
     */
    async fetchBalanceRecords(params?: { page?: number; limit?: number }) {
      try {
        const data = await accountAPI.getBalanceRecords(params);
        console.log('Raw API response:', data); // 调试日志
        
        // 直接使用后端返回的数据，不做转换
        this.balanceRecords = data;
        console.log('Stored balanceRecords:', this.balanceRecords); // 调试日志
        
        // 更新余额信息
        if (data && data.balance_summary) {
          this.balance = data.balance_summary.total_balance || 0;
        }
        return data;
      } catch (err) {
        console.error('获取余额明细失败:', err);
        throw err;
      }
    },
    
    /**
     * 清空错误信息
     */
    clearError() {
      this.error = null;
    }
  }
});